/**
 * 格子处理
 */
var DataMgr = require('DataMgr');
cc.Class({
    extends: cc.Component,
    /**
     * eliminate: true有护盾，无法被直接消除
     * fixed: true固定位置，无法被消除
     */

    properties: {
        latticeX: 0,//纵向位置，从0开始计数，如左下角纵向第二个{latticeX: 1, latticeY: 0}
        latticeY: 0,//横向位置，从0开始计数，如左下角横向第二个{latticeX: 0, latticeY: 1}
        countX: 1,//行计数
        countY: 1,//列计数
        storage: false,//是否被储存进LatticeMgr的vector数组
        ThinIceN: {
            type: cc.Node,
            default: null
        },
        ShieldN: {
            type: cc.Node,
            default: null
        },
        ElementN: {
            type: cc.Node,
            default: null
        },
        edgeUp: {
            type: cc.Node,
            default: null
        },
        edgeDown: {
            type: cc.Node,
            default: null
        },
        edgeLeft: {
            type: cc.Node,
            default: null
        },
        edgeRight: {
            type: cc.Node,
            default: null
        },
        effectN1: {
            type: sp.Skeleton,
            default: null
        },
        effectN2: {
            type: sp.Skeleton,
            default: null
        },
        clickN: {
            type: cc.Node,
            default: null
        },
    },


    // onLoad () {},

    start() {
        var self = this;
        //添加操作（格子没有元素 处于锤子道具状态 步数小于0 固定的（不可移动的 如石头 冰块等）锚 之类的 return掉  ）
        this.node.on(cc.Node.EventType.TOUCH_START, function (event) {
            cc.vv.netRootjs.dispatchEvent("double");
            if (self.ElementN == null) {
                return;
            }
            if (Globals.mallet == true) {
                cc.vv.netRootjs.dispatchEvent("mallet", this.node);
                return;
            }
            if (Globals.boom == true) {
                cc.vv.netRootjs.dispatchEvent("boom", this.node);
                return;
            }
            if (Globals.model != "infinite") {
                if (Globals.doorlimit <= 0) {
                    return;
                }
            }
            if (self.fixed == true || self.ElementN == null) {
                return;
            }
            if (self.getState() == Enum.State.STATE_ANCHOR) {
                return;
            }
            var agr = { data: self.node, type: Enum.NONE }
            cc.vv.netRootjs.dispatchEvent("moveTo", agr);
        }, this);
        this.node.on(cc.Node.EventType.TOUCH_END, function (event) {
            // if(Globals.model!="infinite"){
            //     if(Globals.doorlimit<=0){
            //         return;
            //     }
            // }
            // if(self.fixed==true||self.ElementN==null){
            //     return;
            // }
            // if(self.getState()==Enum.State.STATE_ANCHOR){
            //     return;
            // }
            // var agr={data:self.node,type:Enum.NONE}
            // cc.vv.netRootjs.dispatchEvent("moveTo",agr);
            // cc.vv.netRootjs.dispatchEvent("double");
            // if(self.ElementN==null){
            //     return;
            // }
            // if(Globals.mallet==true){
            //     cc.vv.netRootjs.dispatchEvent("mallet",this.node);
            // }
        }, this);
        //移出格子范围释放时判定移动方向
        this.node.on(cc.Node.EventType.TOUCH_CANCEL, function (event) {
            if (Globals.model != "infinite") {
                if (Globals.doorlimit <= 0) {
                    return;
                }
            }
            if (self.fixed == true || self.ElementN == null) {
                return;
            }
            if (self.getState() == Enum.State.STATE_ANCHOR) {
                return;
            }
            let pos = event.getLocation()
            var eventpos = self.node.convertToNodeSpace(pos);
            var agr;
            if (eventpos.y >= 0 && eventpos.y <= this.node.height) {
                if (eventpos.x > this.node.width) {
                    //右移动
                    agr = { data: self.node, type: Enum.RIGHT }
                }
                else if (eventpos.x < 0) {
                    //左移动
                    agr = { data: self.node, type: Enum.LEFT }
                }
            }
            else if (eventpos.x >= 0 && eventpos.x <= this.node.width) {
                if (eventpos.y > this.node.height) {
                    //上移动
                    agr = { data: self.node, type: Enum.UP }
                }
                else if (eventpos.y < 0) {
                    //下移动
                    agr = { data: self.node, type: Enum.DOWN }
                }
            }
            else {
                return;
            }
            cc.vv.netRootjs.dispatchEvent("moveTo", agr);
        }, this);
        //冰块监听 附近有元素消失时消掉一层冰块
        cc.vv.netRoot.on("Ice", function (arg) {
            if (self.shield.hp > 0 && self.eliminate == true) {
                if ((Math.abs(arg.X - self.latticeX) == 1 && Math.abs(arg.Y - self.latticeY) == 0)
                    || (Math.abs(arg.X - self.latticeX) == 0 && Math.abs(arg.Y - self.latticeY) == 1)) {
                    self.removeElementN();
                }
            }
        }, cc.vv.netRoot);
    },
    onDestroy() {
        cc.vv.netRoot.off("Ice");
    },
    //初始化2是随机一种格子
    init: function (id, x, y) {
        let data;
        if (id == 2) {
            let random = Math.floor(Math.random() * 100) + 1;
            if (random > 80) {
                let randomId = Math.floor(Math.random() * DataMgr.latticeDtMgr.getDataLeng());
                data = DataMgr.latticeDtMgr.getDataByInx(randomId);
                while (data.elementID != 0 || data.show == false) {
                    randomId = Math.floor(Math.random() * DataMgr.latticeDtMgr.getDataLeng());
                    data = DataMgr.latticeDtMgr.getDataByInx(randomId);
                }
            }
            else {
                data = DataMgr.latticeDtMgr.getDataByID(1);
            }
        }
        else {
            data = DataMgr.latticeDtMgr.getDataByID(id);
        }

        this.id = data.id;
        this.latticeX = x;
        this.latticeY = y;
        // if (this.latticeX % 2 == 0) {
        //     if (this.latticeY % 2 == 0) {
        //         this.img = "lattice_1";
        //     }
        //     else {
        //         this.img = "lattice_2";
        //     }
        // }
        // else {
        //     if (this.latticeY % 2 == 0) {
        //         this.img = "lattice_2";
        //     }
        //     else {
        //         this.img = "lattice_1";
        //     }
        // }
        // this.img="lattice";

        //加载图片
        let atlasPath = cc.vv.LocalData.getData("atlasPath");
        // var spriteCom = this.getComponent(cc.Sprite);
        // cc.vv.UIComment.loadSpriteFrame(this.img, spriteCom, atlasPath);

        let spriteCom2 = this.clickN.getComponent(cc.Sprite);
        cc.vv.UIComment.loadSpriteFrame("lattice_click", spriteCom2, atlasPath);


        this.thinIce = {};
        this.thinIce.hp = data.thinIce.hp;
        this.thinIce.img = data.thinIce.img;

        this.shield = {};
        this.shield.hp = data.shield.hp;
        this.shield.img = data.shield.img;
        this.shield.eliminate = data.shield.eliminate;

        this.show = data.show;//是否可见
        this.born = data.born;//是否是出生点
        this.elementHp = data.elementHp;
        this.elementID = data.elementID;
        //将薄冰和护盾加载父节点上（层级显示）
        let parent = this.node.getParent();
        this.node.zIndex = 0;
        //薄冰
        this.ThinIceN.setParent(parent);
        this.ThinIceN.position = this.node.position;
        this.ThinIceN.zIndex = 1;
        //护盾
        this.ShieldN.setParent(parent);
        this.ShieldN.position = this.node.position;
        this.ShieldN.zIndex = 5;

        this.effectN1.node.setParent(parent);
        this.effectN1.node.position = this.node.position;
        this.effectN1.node.zIndex = 10;

        this.effectN2.node.setParent(parent);
        this.effectN2.node.position = this.node.position;
        this.effectN2.node.zIndex = 10;

        this.clickN.setParent(parent);
        this.clickN.position = this.node.position;
        this.clickN.zIndex = 8;

        this.clickN.active = false;

        this.changeThinIce();
        this.changeShield();
    },
    //恢复未判定时候的状态
    reset: function () {
        this.countX = 1;
        this.countY = 1;
        this.storage = false;
    },
    //拿到元素ID
    getId: function () {
        if (this.ElementN == null) {
            return 0;
        }
        this.ElementCom = this.ElementN.getComponent('Element');
        // return this.ElementCom.img;
        return this.ElementCom.name;
    },
    //拿到元素状态
    getState: function () {
        if (this.ElementN == null) {
            return 0;
        }
        this.ElementCom = this.ElementN.getComponent('Element');
        return this.ElementCom.state;
    },
    //修改元素状态
    setState: function (data) {
        if (this.ElementN == null) {
            return 0;
        }
        this.ElementCom = this.ElementN.getComponent('Element');
        this.ElementCom.changeState(data);
    },
    //改变碎冰样子
    changeThinIce: function () {
        if (this.thinIce.hp == 0) {
            this.ThinIceN.active = false;
        }
        else {
            //加载图片
            let atlasPath = cc.vv.LocalData.getData("atlasPath");
            var spriteCom = this.ThinIceN.getComponent(cc.Sprite);
            cc.vv.UIComment.loadSpriteFrame(this.thinIce.img[this.thinIce.hp - 1], spriteCom, atlasPath);
        }
    },
    //修改碎冰血量
    setThinIceHp: function (hp) {
        if (this.thinIce.hp == hp) {
            return;
        }
        this.thinIce.hp = hp;
        if (this.thinIce.hp == 0) {
            cc.vv.netRootjs.dispatchEvent("doorCount", "C01");
        }
        this.changeThinIce();
    },
    //改变护盾样子（冰块 石头）
    changeShield: function () {
        if (this.shield.hp == 0) {
            this.ShieldN.active = false;
            this.fixed = false;
            this.eliminate = false;
            if (this.show == false) {
                this.fixed = true;
                this.eliminate = true;
            }
            return;
        }
        else {
            this.fixed = true;//true是固定 false是不固定
            this.eliminate = this.shield.eliminate;//true是不可消除，false是可消除

            let atlasPath = cc.vv.LocalData.getData("atlasPath");
            var spriteCom = this.ShieldN.getComponent(cc.Sprite);
            cc.vv.UIComment.loadSpriteFrame(this.shield.img[this.shield.hp - 1], spriteCom, atlasPath);
        }
    },
    //改变护盾血量（冰块 石头）
    setShieldHp: function (hp) {
        if (this.shield.hp == hp) {
            return;
        }
        this.shield.hp = hp;
        if (this.shield.hp == 0) {
            if (this.eliminate == true) {
                cc.vv.netRootjs.dispatchEvent("doorCount", "C04");
            }
            else {
                cc.vv.netRootjs.dispatchEvent("doorCount", "C03");
            }
        }
        this.changeShield();
    },
    //改变格子元素 （交换）
    changeElementN: function (LatticeN) {
        let LatticeCom = LatticeN.getComponent('Lattice');
        if (LatticeCom.ElementN == null) {
            return;
        }
        if (this.ElementN === null) {
            this.ElementN = LatticeCom.ElementN;
            LatticeCom.ElementN = null;
            this.ElementN.stopAllActions();
            if (this.latticeX == 0) {
                if (this.getState() == Enum.State.STATE_ANCHOR) {
                    // cc.vv.netRootjs.dispatchEvent("doorCount","C07");
                    this.scheduleOnce(function () { this.removeAnchor() }, Enum.RepairTime);
                }
            }
            let ElemenCom = this.ElementN.getComponent('Element');
            ElemenCom.madeAction(this.node);
        }
        else {
            let letElementN = this.ElementN;
            this.ElementN = LatticeCom.ElementN;
            let action1 = cc.moveTo(Enum.MoveTime, cc.v2(this.node.x, this.node.y));
            this.ElementN.stopAllActions();
            this.ElementN.runAction(action1);

            LatticeCom.ElementN = letElementN;
            let action2 = cc.moveTo(Enum.MoveTime, cc.v2(LatticeCom.node.x, LatticeCom.node.y));
            LatticeCom.ElementN.stopAllActions();
            LatticeCom.ElementN.runAction(action2);
        }
        this.reset();
        LatticeCom.reset();

    },
    //消除特效
    removeEffect: function (state) {
        if (state == Enum.State.STATE_CROSS) {
            this.effectN1.setAnimation(0, "changtiaoxiaochu", false);
            this.effectN2.setAnimation(0, "changtiaoxiaochu", false);
        }
        else if (state == Enum.State.STATE_COLUMN) {
            this.effectN2.setAnimation(0, "changtiaoxiaochu", false);
        }
        else if (state == Enum.State.STATE_LINE) {
            this.effectN1.setAnimation(0, "changtiaoxiaochu", false);
        }
        else {
            this.effectN1.setAnimation(0, "xiaochu", false);
        }
    },
    //消除锚
    removeAnchor: function () {
        this.removeElementN();
        cc.vv.netRootjs.dispatchEvent("repair");
    },
    //消除元素
    removeElementN: function () {
        this.ElementCom = this.ElementN.getComponent('Element');
        ///FIXME:现在计算分数在LatticeMgr的removeElementN中
        // cc.vv.netRootjs.dispatchEvent("score",this.ElementCom.score);        

        ///FIXME:去掉原本的计算分数方法，现在一个元素一分
        // if(this.countX>=3&&this.countY>=3){
        //     // cc.vv.MusicComment.playSFX("amazing");
        //     cc.vv.netRootjs.dispatchEvent("score",Enum.five);//5连
        // }
        // else if(this.countX>=5||this.countY>=5){
        //     // cc.vv.MusicComment.playSFX("amazing");
        //     cc.vv.netRootjs.dispatchEvent("score",Enum.five);//5连
        // }
        // else if(this.countX>3||this.countY>3){
        //     // cc.vv.MusicComment.playSFX("great");
        //     cc.vv.netRootjs.dispatchEvent("score",Enum.four);//4连
        // }
        // else if(this.countX==3||this.countY==3){
        //     // cc.vv.MusicComment.playSFX("good");
        //     cc.vv.netRootjs.dispatchEvent("score",Enum.three);//3连
        // }
        //自己不是冰块被消除时发送冰块事件（冰块接收判断是否在自己周边 在则自己消一层冰块）
        if (this.eliminate != true) {
            let arg = { X: this.latticeX, Y: this.latticeY };
            cc.vv.netRootjs.dispatchEvent("Ice", arg);
        }
        //护盾消失的情况下 消除薄冰血量
        if (this.thinIce.hp > 0 && this.shield.hp <= 0) {
            this.setThinIceHp(this.thinIce.hp - 1);
        }
        //护盾血量大于0则消护盾血量
        if (this.shield.hp > 0) {
            this.setShieldHp(this.shield.hp - 1);
            this.reset();
            return;
            // if(this.eliminate==true){
            //     this.setShieldHp(this.shield.hp-1);
            //     this.reset(); 
            //     return;
            // }
            // this.setShieldHp(this.shield.hp-1);
        }
        //元素护盾血量大于0则消元素护盾血量
        if (this.ElementCom.shieldHp > 0) {
            this.ElementCom.setShieldHp(this.ElementCom.shieldHp - 1);
        }
        //当元素不是宝石（横竖消同类消之类）时，消除元素使通过元素连成的数量来改变元素
        else if (this.ElementCom.state == Enum.State.STATE_NOEN) {
            cc.vv.netRootjs.dispatchEvent("doorCount", this.getId());
            this.removeEffect(this.getState());
            if (this.countX >= 3 && this.countY >= 3) {
                this.ElementCom.changeState(Enum.State.STATE_CROSS);
            }
            //去除大风车
            // else if(this.countX>=5||this.countY>=5){
            //     this.ElementCom.changeState(Enum.State.STATE_SIMILAR);
            // }
            else if (this.countX > 3) {
                this.ElementCom.changeState(Enum.State.STATE_LINE);
            }
            else if (this.countY > 3) {
                this.ElementCom.changeState(Enum.State.STATE_COLUMN);
            }
            else {
                this.ElementCom.node.removeFromParent();
                this.ElementN = null;
            }
        }
        else if (this.ElementCom.state == Enum.State.STATE_SIMILAR) {
            // cc.vv.MusicComment.playSFX("excellent");
            this.removeEffect(this.getState());
            // cc.vv.netRootjs.dispatchEvent("score",Enum.random);//随机宝石
            cc.vv.netRootjs.dispatchEvent("doorCount", this.getId());
            this.ElementCom.node.removeFromParent();
            this.ElementN = null;
        }
        else if (this.ElementCom.state == Enum.State.STATE_ANCHOR) {
            this.removeEffect(this.getState());
            cc.vv.netRootjs.dispatchEvent("doorCount", "C07");
            this.ElementCom.node.removeFromParent();
            this.ElementN = null;
        }
        else {
            // cc.vv.MusicComment.playSFX("excellent");
            cc.vv.netRootjs.dispatchEvent("doorCount", this.getId());
            this.removeEffect(this.getState());
            cc.vv.netRootjs.dispatchEvent("state", this.node);
            this.ElementCom.node.removeFromParent();
            this.ElementN = null;
        }
        // this.move=false;
        this.reset();
    },

    //点击时的提示
    hint: function () {
        if (this.ElementN == null) {
            return 0;
        }
        this.ElementCom = this.ElementN.getComponent('Element');
        this.ElementCom.selfHint();
        this.clickN.active = true;
    },
    hintOff: function () {
        if (this.ElementN == null) {
            return 0;
        }
        this.ElementCom = this.ElementN.getComponent('Element');
        this.ElementCom.selfHintOff();
        this.clickN.active = false;
    }
    // update (dt) {},
});
